<?php
namespace app\member\controller;
use think\Db;
class Software extends Common{
    function __construct(){
        parent::__construct();
        $navs=config("navs.1.children");
        $this->assign('_nav',json_encode($navs,JSON_UNESCAPED_UNICODE));
    }
    /**
     * 账号列表
     * @param  string  $dev        [description]
     * @param  integer $addVisible [description]
     * @param  string  $val        [description]
     * @param  string  $type       [description]
     * @return [type]              [description]
     */
    function index($dev='0',$addVisible=0,$val='',$type='name'){
        $user=$this->user;
        $device=model('device')->readAll(['member_id'=>$user['id']],0,[
            'field'=>'id,name'
        ]);
        $params=[
            'dev'=>$dev,
            'val'=>$val,
            'type'=>$type,
        ];
        $this->assign('device',$device);
        $where=[
            'member_id'=>$user['id'],
        ];
        $_type=['name','number'];
        if(in_array($type,$_type)){
            $where[$type]=[$type,'like',"%$val%"];
        }
        if($dev>0){
            $where['device_id']=$dev;
        }
        $list=model($this->table)->readAll($where,true,[
            'with'=>['device'=>function($query){
                return $query->field('id,name');
            },'type'],
            'order'=>'sort,id',
        ]);
        $list->appends($params);
        $this->assign('addVisible',$addVisible);
        $this->assign('dev',$dev);
        $this->assign('params',$params);
        $this->assign('list',$list);
        $type=model('soft_type')->readAll(['status'=>1]);
        $this->assign('type',$type);
        $device=model('device')->readAll(['member_id'=>$user['id'],'status'=>1]);
        $this->assign('device',$device);
        return view();
    }
    function add($id=0){
        $user=$this->user;
        $software=[];
        if($id>0){
            $software=model($this->table)->read(['id'=>$id,'member_id'=>$user['id']]);
            //该用户下不存在该设备做添加操作
            if(empty($software)){
                $id=0;
            }
        }
        if(request()->isPost()){
            $data=[
                'id'=>$id,
                'name'=>input('name/s',''),
                'number'=>input('number/s',''),
                'type_id'=>input('type_id/d',0),
                'device_id'=>input('device_id/d',0),
                'sex'=>input('sex/d',0),
                'body_id'=>input('body_id/d',0),
                'login_name'=>input('login_name/s',''),
                'login_pwd'=>input('login_pwd/s',''),
                'tel'=>input('tel/s',''),
                'remark'=>input('remark/s',''),
            ];
            $validate=$this->validate($data,[
                'number|'.lang('Number')=>'require',
                'type_id|'.lang('Type')=>'require',
                'device_id|'.lang('Device')=>'require',
                'login_name|'.lang('Login name')=>'require',
                'login_pwd|'.lang('Login password')=>'require',
            ]);
            if(true!==$validate){
                $this->error($validate);
            }
            // 验证设备是否该用户所有
            $has=model('device')->read(['member_id'=>$user['id'],'id'=>$data['device_id']]);
            if(empty($has)){
                $this->error(lang('The equipment does not exist'));
            }

            $result=[];
            
            if($id>0){
                $hasBodyId=model('software')->where(['body_id'=>$data['body_id'],'device_id'=>$data['device_id'],'id'=>['id','<>',$id]])->count();
                if($hasBodyId){
                    $this->error('该设备下已存在该分身ID');
                }
                $result=model($this->table)->edit($data);
            }else{
                $data['s_time']=time();
                $data['sort']=time();
                // 判断账号是否到达上限，若到达上限则返回错误，不添加数据
                // 查找用户表，获取该用户的设备上限值
                $member = Db::name('member')->where('id','eq',$user['id'])->field('id,max_weixin')->find();
                $limit = $member['max_weixin'];
                // 统计已有设备数量
                $quant = Db::name('software')->where('device_id','eq',$data['device_id'])->where('type_id','eq',1)->count();
                // echo json_encode($limit);die;
                if ($limit <= $quant) {
                    $this->error('添加失败！该设备的微信号已达到上限！');
                }
                $BodyId=model('software')->where(['device_id'=>$data['device_id']])->max('body_id');
                $data['body_id']=$BodyId;
                if($quant>0){
                    $data['body_id']=$BodyId+1;
                }
                $data['member_id']=$user['id'];
                $result=model($this->table)->add($data);
            }

            if(empty($result)){
                $this->error(lang('Failed operation'));
            }
            $this->success(lang('Successful operation'));
        }
    }
    // 用于Excel 导入设备 操作
    function addAll(){
        if(request()->isPost()){
            $data=input('data/a',[]);
            if(empty($data)||!is_integer(key($data))){
                $this->error(lang('The data does not exist or the format is incorrect'));
            }
            $time=time();
            $member_id=$this->user['id'];
            $type=[];
            $device=[];
            $softwares=[];
            $BodyId=model('software')->where(['device_id'=>$data['device_id']])->max('body_id');
            foreach ($data as $k => $v) {
                // 验证类型
                $type_id=0;
                $has_type=array_keys($type,$v[2],true);
                if(empty($has_type)){
                    $has_type=model('soft_type')->read(['name'=>$v[2]],'id,name');
                    if(empty($has_type)){ // 当前设备未添加
                        $has_type=model('soft_type')->add([
                            'name'=>$v[2],
                            'remark'=>lang('Import an account when you add')
                        ]);
                    }
                    if(!empty($has_type)){
                        $type_id=$has_type['id'];
                        $type[$has_type['id']]=$has_type['name'];
                    }
                }else{
                    $type_id=$has_type[0];
                }
                // 验证设备是否该用户所有
                $device_id=0;
                $has_device=array_keys($device,$v[3],true);
                if(empty($has_device)){
                    $has_device=model('device')->read(['member_id'=>$member_id,'name'=>$v[3]],'id,name');
                    if(empty($has_device)){ // 当前设备未添加
                        $has_device=model('device')->add([
                            'name'=>$v[3],
                            'member_id'=>$member_id,
                            's_time'=>$time,
                            'remark'=>lang('Import an account when you add')
                        ]);
                    }
                    if(!empty($has_device)){
                        $device_id=$has_device['id'];
                        $device[$has_device['id']]=$has_device['name'];
                    }
                }else{
                    $device_id=$has_device[0];
                }
                if($type_id&&$device_id){
                    $softwares[$k]=[
                        'name'=>$v[0],
                        'number'=>$v[1],
                        'type_id'=>$type_id,
                        'device_id'=>$device_id,
                        'sex'=>$v[4],
                        'login_name'=>$v[5],
                        'login_pwd'=>$v[6],
                        'tel'=>$v[7],
                        'remark'=>isset($v[8])?$v[8]:'',
                        'body_id'=>$BodyId++,
                        's_time'=>$time,
                        'sort'=>$time,
                        'member_id'=>$member_id,
                    ];
                }
            }
            $add=model($this->table)->add($softwares);

            if(empty($add)){
                $this->error(lang('Failed operation'));
            }
            $this->success(lang('Successful operation'));
        }
    }
    /**
     * 账号列表的上下移动
     * @param  integer  $device_id 设备ID
     * @param  array    $val [{task_id,sort}]
     * @return json
     */
    function record($val=[]){
        if(request()->isAjax()||request()->isPost()){
            if(empty($val)){
                $this->error('缺少数据');
            }
            $ids=[];
            
            foreach($val as $v) {
                if(!isset($v['id'])||$v['id']<=0||!isset($v['sort'])||$v['sort']<0){
                    $this->error('数据有误');
                }
                array_push($ids,$v['id']);
            }
            $where=[
                'member_id'=>$this->user['id'],
                'id'=>['id','in',$ids],
            ];
            $nums=db($this->table)->where($where)->count();
            if($nums!==count($ids)){
                $this->error('数据有误');
            }
            $save=model($this->table)->edit($val);
            if(!$save){
                $this->error(lang('Failed operation'));
            }
            $this->success(lang('Successful operation'));
        }
    }
    function del($id=0){
        if(request()->isAjax()||request()->isPost()){
            $ids=input('ids/a',[]); // 多项删除
            if($id<=0&&empty($ids)){
                $this->error(lang('Data does not exist'));
            }
            $member_id=$this->user['id'];
            $where=['id'=>$id,'member_id'=>$member_id];
            $_map=['soft_id'=>$id];
            if(!empty($ids)){
                $where=[
                    'member_id'=>$member_id,
                    'id'=>['id','in',$ids]
                ];
                $_map=[
                    'soft_id'=>['soft_id','in',$ids],
                ];
            }
            
            $del=model($this->table)->del($where);
            if($del){
                // 删除该设备上的微信 记录
                model('weixinlogs')->del($_map);
                $this->success(lang('Successful operation'));
                die;
            }
            $this->error(lang('Failed operation'));
        }
    }
    function close($id=0){
        if(request()->isAjax()||request()->isPost()){
            $ids=input('ids/a',[]); // 多项删除
            if($id<=0&&empty($ids)){
                $this->error(lang('Data does not exist'));
            }
            $member_id=$this->user['id'];
            $where="id={$id} and member_id={$member_id}";
            if(!empty($ids)){
                $idStr='('.implode(',', $ids).')';
                $where="member_id={$member_id} and id in {$idStr}";
            }
            
            $close=model($this->table)->close($where,'status',true);
            $this->success(lang('Successful operation'));
        }
    }
}
